package com.web.shop.service.impl;

import com.web.shop.mapper.TbContentCategoryMapper;
import com.web.shop.mapper.TbContentMapper;
import com.web.shop.pojo.TbContent;
import com.web.shop.pojo.TbContentCategory;
import com.web.shop.pojo.TbContentExample;
import com.web.shop.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper contentMapper;

	@Autowired
	private TbContentCategoryMapper contentCategoryMapper;


	@Autowired
	private RedisTemplate redisTemplate;
//
//	@Autowired
//	private RedisTemplate redisTemplate;
    @Override
    public List<TbContentCategory> findAllcate() {
	       return contentCategoryMapper.selectByExample(null);
}

	@Override
	public List<TbContent> findAll() {
		return contentMapper.selectByExample(null);
	}

	@Override
	public void add(TbContent content) {
		
		contentMapper.insert(content);	
		// 清除缓存
		redisTemplate.boundHashOps("content").delete(content.getCategoryId());
	}

	@Override
	public void update(TbContent content){
		TbContent oldContent = contentMapper.selectByPrimaryKey(content.getId());
		// 清除之前分类的广告缓存
		redisTemplate.boundHashOps("content").delete(oldContent.getCategoryId());
		
		contentMapper.updateByPrimaryKey(content);
		// 清除缓存
		if(content.getCategoryId() != oldContent.getCategoryId()){
			redisTemplate.boundHashOps("content").delete(content.getCategoryId());
		}
		
	}	
	

	@Override
	public TbContent findOne(Long id){
		return contentMapper.selectByPrimaryKey(id);
	}

	@Override
	public void delete(Long id) {
    	TbContent tbContent = contentMapper.selectByPrimaryKey(id);
    	redisTemplate.boundHashOps("content").delete(tbContent.getCategoryId());
	contentMapper.deleteByPrimaryKey(id);
}

	/**
	 * 首次访问时，如果redis没有数据，就访问数据库，把数据存到redis
	 * 后续访问时，直接查询redis
	 */
	@Override
	public List<TbContent> findByCategoryId(Long categoryId) {

		List<TbContent> list = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);

		if(list==null){
			TbContentExample example = new TbContentExample();
			TbContentExample.Criteria criteria = example.createCriteria();

			criteria.andStatusEqualTo("1");

			criteria.andCategoryIdEqualTo(categoryId);
			// 排序
			example.setOrderByClause("sort_order");

			list = contentMapper.selectByExample(example);

			redisTemplate.boundHashOps("content").put(categoryId, list);
		}else{

		}
		return list;
	}
}